<?php
declare(strict_types = 1);

/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */
namespace App\Component;

use App\Constants\ChatCode;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Codec\Json;

class RedisUserSever
{

    public $redis;

    public function __construct() {
        $container = ApplicationContext::getContainer();
        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
    }



    public function getUserKey()
    {
        return ChatCode::USER_INFO;
    }

    public function getUserFdKey($id)
    {
        return ChatCode::USER_INFO ."_USER:". $id;
    }

    public function getFdUserKey($fd)
    {
        return ChatCode::USER_INFO ."_FD:". $fd;
    }


    // user 下所有 fd
    public function getUserAllFD($id)
    {
        return $this->redis->hGetAll($this->getUserFdKey($id));
    }
    public function getUserFD($fd, $id)
    {
        return $this->redis->hget($this->getUserFdKey($id), (string)$fd);
    }
    public function setUserFD($fd, $id)
    {
        return $this->redis->hset($this->getUserFdKey($id), (string)$fd, $fd);
    }
    public function delUserFD($fd, $id)
    {
        return $this->redis->hdel($this->getUserFdKey($id), (string)$fd);
    }


    // fd 对应 user
    public function getUserByFd($fd)
    {
        return $this->redis->get($this->getFdUserKey($fd));
    }

    public function setUserByFd($fd, $user)
    {
        return $this->redis->set($this->getFdUserKey($fd), $user);
    }

    public function delUserByFd($fd)
    {
        return $this->redis->del($this->getFdUserKey($fd));
    }


    public function getUserInfo($userId)
    {
        return $this->redis->get($this->getUserKey().":{$userId}");
    }

    public function getUserByToken($token)
    {
        return $this->redis->get((string)$token);
    }

    public function setUserToken($user, $time)
    {
        $this->redis->set($this->getUserKey().":{$user["id"]}", (string)json::encode($user), $time);
        $this->redis->set($user["token"], (string)$user["id"], $time);
    }

    public function delUserInfo($key)
    {
        $this->redis->del($key);
    }
}

